package com.gfxy.educational.quartz;

import com.gfxy.commons.spring.SpringContextHolder;
import com.gfxy.educational.service.JobTimeTypeService;
import com.gfxy.educational.service.QuartzService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author: lijixin 2019-05-23
 */
public class JobTimeShiftTask implements Job {

    public static final String SUMMER_TIME = "summerTime";
    public static final String WINTER_TIME = "winterTime";
    private static final Logger logger = LoggerFactory.getLogger(JobTimeShiftTask.class);


//    @Autowired
//    private QuartzService quartzService;
//    @Autowired
//    private JobTimeTypeService jobTimeTypeService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String executeTriggerName = jobExecutionContext.getTrigger().getKey().getName();
        logger.info("开始切换工作时间，当前触发器名字为：" + executeTriggerName);
        QuartzService quartzService = SpringContextHolder.getBean("quartzService");
        JobTimeTypeService jobTimeTypeService =  SpringContextHolder.getBean("jobTimeTypeService");
        if(executeTriggerName.equals(SUMMER_TIME)) {

            jobTimeTypeService.shiftJobTimeType("0","1");
            try {
                quartzService.pauseTrigger("0");
                quartzService.startTrigger("1");
            } catch (SchedulerException e) {
                throw new JobExecutionException(e);
            }
        } else {

            jobTimeTypeService.shiftJobTimeType("1","0");
            try {
                quartzService.pauseTrigger("1");
                quartzService.startTrigger("0");
            } catch (SchedulerException e) {
                throw new JobExecutionException(e);
            }


        }

        try {
            Scheduler scheduler = jobExecutionContext.getScheduler();
            for (String pausedTriggerGroup : scheduler.getPausedTriggerGroups()) {
                System.out.println(pausedTriggerGroup);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }
}
